<!--  -->
<template>
  <div class="user-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-input placeholder="请输入搜索内容" v-model="query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="insertUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表数据展示 -->
      <div class="user-table">
        <el-table :data="userList" border stripe style="width: 100%">
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#409EFF"
                inactive-color="#DCDFE6"
                @change="handleSwitch(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-row>
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="updateUserList(scope.row)"
                ></el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteUserById(scope.row.id)"
                ></el-button>
                <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                  <el-button
                    type="warning"
                    size="mini"
                    icon="el-icon-setting"
                    @click="showGrantRoleDialog(scope.row)"
                  ></el-button>
                </el-tooltip>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页信息 -->
      <div class="user-page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加新用户"
      :visible.sync="insertUserDialogVisible"
      width="50%"
      @close="resetUserForm('insertUserRef')"
    >
      <!-- 内容主体 -->
      <el-form
        :model="insertUserForm"
        :rules="userFormRules"
        ref="insertUserRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="insertUserForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="insertUserForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" v-model="insertUserForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input type="tel" v-model="insertUserForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="insertUserDialogVisible = false">取消</el-button>
        <el-button type="info" @click="resetUserForm('insertUserRef')">重置</el-button>
        <el-button type="primary" @click="insertUser('insertUserRef')">提交</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="updateUserDialogVisible"
      width="50%"
      @close="resetUserForm('updateUserRef')"
    >
      <!-- 内容主体 -->
      <el-form
        :model="updateUserForm"
        :rules="userFormRules"
        ref="updateUserRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateUserForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" v-model="updateUserForm.email" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input type="tel" v-model="updateUserForm.mobile" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="updateUserDialogVisible = false">取消</el-button>
        <el-button type="info" @click="resetUserForm('updateUserRef')">重置</el-button>
        <el-button type="primary" @click="updateUser('updateUserRef')">提交</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="grantedRole.grantRoleDialogVisible"
      width="50%"
      @close="resetGrantRole"
    >
      <div>
        <p>当前用户：{{ grantedRole.grantRoleUser.username }}</p>
        <p>用户角色：{{ grantedRole.grantRoleUser.role_name }}</p>
        <el-select v-model="grantedRole.value" placeholder="选择角色">
          <el-option
            v-for="item in grantedRole.roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id+'='+item.roleName"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="grantedRole.grantRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="grantRole">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 校验邮箱
    const checkEmail = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('邮箱不能为空，请重新输入'))
      }
      // 校验邮箱规则
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*(\.\w+([-.]\w+)*)+$/

      if (!regEmail.test(value)) {
        return callback(new Error('输入邮箱格式不正确，请重新输入'))
      }
      callback()
    }

    // 校验手机号码
    const checkMobile = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('手机号码不能为空，请重新输入'))
      }
      // 校验手机号规则
      const regMobile = /^([1][3,4,5,6,7,8,9])\d{9}$/
      if (!regMobile.test(value)) {
        return callback(new Error('输入手机号码格式不正确，请重新输入'))
      }
      callback()
    }
    return {
      userList: [],
      total: 0,
      query: '',
      pagenum: 1,
      pagesize: 5,
      // 控制添加用户对话框显示和隐藏
      insertUserDialogVisible: false,
      // 控制修改用户对话框显示和隐藏
      updateUserDialogVisible: false,
      // 添加用户表单数据
      insertUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      updateUserForm: {},
      // 添加用户表单数据的验证规则
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度3~20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度6~18个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      grantedRole: {
        grantRoleDialogVisible: false,
        grantRoleUser: {},
        // 角色列表
        roleList: [],
        value: ''
      }
    }
  },

  created() {
    this.getUserList()
    this.getRoleList()
  },

  methods: {
    // 获取用户列表
    getUserList() {
      this.axios
        .get('users', {
          params: {
            query: this.query,
            pagenum: this.pagenum,
            pagesize: this.pagesize
          }
        })
        .then(resp => {
          if (resp.meta.status === 200) {
            this.userList = resp.data.users
            this.total = resp.data.total
          } else {
            this.$message.error('获取侧边栏菜单列表失败')
          }
        })
    },
    // 处理分页每页条目改变
    handleSizeChange(val) {
      this.pagesize = val
      this.getUserList()
    },
    // 处理分页当前页码改变
    handleCurrentChange(val) {
      this.pagenum = val
      this.getUserList()
    },
    // 处理状态开关切换
    handleSwitch(user) {
      this.axios.put(`users/${user.id}/state/${user.mg_state}`).then(resp => {
        if (resp.meta.status !== 200) {
          this.$message.error('用户状态切换失败')
          user.mg_state = !user.mg_state
        }
        this.$message.success({
          message: '用户状态切换成功',
          duration: 500
        })
      })
    },
    // 用户表单重置
    resetUserForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 添加用户提交
    insertUser(formName) {
      // 校验邮箱和手机号码
      this.$refs[formName].validate(valid => {
        if (!valid) {
          // 校验失败
          return this.$message.error('表单数据格式不正确，请重新输入')
        }
        // 校验成功
        this.axios.post('users', this.insertUserForm).then(resp => {
          if (resp.meta.status !== 201) {
            // 添加失败
            return this.$message.error('添加用户失败，请重新添加')
          }
          // 添加成功
          // 1、重新获取用户数据列表
          this.getUserList()
          // 2、关闭对话框
          this.insertUserDialogVisible = false
        })
      })
    },
    // 弹出修改用户信息对话框
    updateUserList(user) {
      // 初始化修改用户表单数据
      let { ...u } = user
      this.updateUserForm = u
      // 显示对话框
      this.updateUserDialogVisible = true
    },
    // 修改用户提交
    updateUser(formName) {
      // 校验邮箱和手机号码
      this.$refs[formName].validate(valid => {
        if (!valid) {
          // 校验失败
          return this.$message.error('表单数据格式不正确，请重新输入')
        }
        // 校验成功
        this.axios
          .put(`users/${this.updateUserForm.id}`, {
            id: this.updateUserForm.id,
            email: this.updateUserForm.email,
            mobile: this.updateUserForm.mobile
          })
          .then(resp => {
            if (resp.meta.status !== 200) {
              // 修改失败
              return this.$message.error('修改用户信息失败')
            }
            // 修改成功
            this.$message.success('修改用户信息成功')
            // 1、重新获取用户数据列表
            this.getUserList()
            // 2、关闭对话框
            this.updateUserDialogVisible = false
          })
      })
    },
    // 删除用户
    deleteUserById(userId) {
      // 删除确认
      this.$confirm('此操作将会永久删除该用户，确定要删除吗', 'Warning', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 确认删除，执行删除操作
          this.axios.delete(`users/${userId}`).then(resp => {
            if (resp.meta.status !== 200) {
              return this.$message.error('删除用户失败')
            }
            // 成功删除，重新获取数据
            this.getUserList()
            this.$message.success('成功删除用户')
          })
        })
        .catch(() => {
          // 取消删除
          this.$message.info('已取消删除')
        })
    },
    // 显示分配角色对话框
    showGrantRoleDialog(user) {
      this.grantedRole.grantRoleDialogVisible = true
      this.grantedRole.grantRoleUser = user
    },
    // 重新分配角色
    grantRole() {
      this.axios
        .put(`users/${this.grantedRole.grantRoleUser.id}/role`, {
          rid: this.grantedRole.value.split('=')[0]
        })
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error('分配角色失败')
          }
          this.grantedRole.grantRoleUser.role_name = this.grantedRole.value.split(
            '='
          )[1]
          this.$message.success({ message: '分配角色成功', duration: 500 })
          this.grantedRole.grantRoleDialogVisible = false
        })
    },
    // 获取角色列表
    getRoleList() {
      this.axios.get('roles').then(resp => {
        if (resp.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.$message.success({ message: '获取角色列表成功', duration: 500 })
        this.grantedRole.roleList = resp.data
      })
    },
    // 重置分配角色对话框
    resetGrantRole() {
      this.grantedRole.value = ''
      this.grantedRole.grantRoleUser = {}
    }
  },

  components: {}
}
</script>

<style lang='scss' scoped>
.user-container {
  .box-card {
    .user-table {
      margin: 10px 0;
      font-size: 12px;
    }
  }
}
</style>
